package com.colabo.j2ee.web.oaf.security.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.map.ListOrderedMap;
import org.springframework.dao.DataAccessException;

import com.colabo.j2ee.web.core.common.CommonConstants;
import com.colabo.j2ee.web.core.exception.ServiceException;
import com.colabo.j2ee.web.core.pkgenerator.IPKGenerator;
import com.colabo.j2ee.web.core.service.impl.DefaultServiceImpl;
import com.colabo.j2ee.web.oaf.security.IDataPermissionManagerService;
import com.colabo.j2ee.web.oaf.security.model.IPDataPermissionVO;

public class DataPermissionManagerServiceImpl extends DefaultServiceImpl implements IDataPermissionManagerService {
	private IPKGenerator keyService = null;

	public Integer[] saveSelfDataPermission(Map objectList) throws ServiceException {
		try {
			// 插入成功的记录数、更新成功的记录数、删除成功的记录数
			int insertCount = 0;
			int updateCount = 0;
			int deleteCount = 0;

			// 删除主键列表、更新bean的列表、新增bean的列表
			String idList = (String) objectList.get(CommonConstants.ID_LIST);
			List insertBeanList = (ArrayList) objectList.get(CommonConstants.INSERT_BEAN_LIST);
			List updateBeanList = (ArrayList) objectList.get(CommonConstants.UPDATE_BEAN_LIST);

			IPDataPermissionVO bean;
			Iterator it;

			// 批量插入记录
			if (insertBeanList.size() > 0) {
				it = insertBeanList.iterator();
				while (it.hasNext()) {
					bean = (IPDataPermissionVO) it.next();
					bean.setId(keyService.getUUIDKey());
					this.save_Hibernate_Object(bean);
					insertCount++;
				}
			}

			// 批量更新记录
			if (updateBeanList.size() > 0) {
				it = updateBeanList.iterator();
				while (it.hasNext()) {
					bean = (IPDataPermissionVO) it.next();
					this.update_Hibernate_Object(bean);
					updateCount++;
				}
			}

			// 批量删除记录
			if (idList.length() > 0) {
				String[] s = idList.split(",");
				if (s.length > 0) {
					for (int i = 0; i < s.length; i++) {
						String sid = s[i];
						String a = sid.replaceAll("'", "");
						String b = a;
						this.deleteByID_Hibernate_Object(IPDataPermissionVO.class, b);
						deleteCount++;
					}
				}
			}

			return new Integer[] { new Integer(insertCount), new Integer(updateCount), new Integer(deleteCount) };
		} catch (DataAccessException dae) {
			throw new ServiceException(dae);
		}
	}

	public void setKeyService(IPKGenerator keyService) {
		this.keyService = keyService;
	}

	public List findAllMetadata() throws ServiceException {
		return null;
	}

	public List findAllMetadataId(String dataPermissionId) throws ServiceException {
		return null;
	}

	public void addMetadataToDataPermission(String metaDataIds, String permissionId, String fields)
			throws ServiceException {
		String[] arr = metaDataIds.split(",");
		if (arr == null) {
			return;
		}

		String delete = "DELETE FROM IP_DP_ASS WHERE DP_ID='" + permissionId + "'";

		String sql = "INSERT INTO IP_DP_ASS(DP_ID,MD_ID) VALUES (?,?)";
		int count = arr.length;
		Connection conn = null;
		PreparedStatement ps = null;
		Statement st = null;
		try {
			conn = getJdbcTemplate().getDataSource().getConnection();
			st = conn.createStatement();
			st.execute(delete);

			st.close();
			ps = conn.prepareStatement(sql);
			String tmp = "";
			for (int i = 0; i < count; i++) {
				tmp = arr[i];
				if (tmp == null || tmp.length() < 1) {
					continue;
				}
				ps.setString(1, permissionId);
				ps.setString(2, tmp);
				ps.addBatch();
			}
			ps.executeBatch();
			ps.close();
		} catch (Exception e) {
			throw new ServiceException(e);
		} finally {
			try {
				if(st != null){
					st.close();
				}
				
				if(ps != null){
					ps.close();
				}
				
				if(conn != null){
					conn.close();
				}
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}

		if (fields == null || fields.length() < 1) {
			fields = "";
		}

		IPDataPermissionVO vo = (IPDataPermissionVO) findByID_Hibernate_Load(IPDataPermissionVO.class, permissionId);
		vo.setDpField(fields);
		save_Hibernate_Object(vo);
	}

	public void addUnitToDataPermission(String unitIds, String permissionId) throws ServiceException {
		String[] arr = unitIds.split(",");

		if (arr == null) {
			return;
		}
		//"DELETE FROM IP_UP_ASS WHERE UP_ID='" + permissionId + "' AND UNIT_ID IN (" + unitIds + ")";
		//getJdbcTemplate().execute(sql);

		String sql;
		List haslist = getUnitIdMap(permissionId);

		sql = "INSERT INTO IP_UP_ASS(UP_ID,UNIT_ID) VALUES (?,?)";
		int count = arr.length;
		Connection conn = null;
		PreparedStatement ps = null;
		try {
			conn = getJdbcTemplate().getDataSource().getConnection();
			ps = conn.prepareStatement(sql);
			String temp = "";
			for (int i = 0; i < count; i++) {
				temp = arr[i];
				
				if (temp == null || temp.length() < 1 ){
					continue;
				}
				temp = temp.replaceAll("'", "");
				if (haslist.contains(temp)){//如果temp不存在或者temp在数据库中已经存在
					continue;
				}
				ps.setString(1, permissionId);
				ps.setString(2, temp);
				ps.addBatch();
			}
			ps.executeBatch();
		} catch (Exception e) {
			throw new ServiceException(e);
		} finally {
			try {
				ps.close();
			} catch (Exception ex) {
				ex.printStackTrace();
			}
			try {
				conn.close();
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}
	}

	public List getUnitIdMap(String permissionId) throws ServiceException {
		String sql = "SELECT UNIT_ID FROM IP_UP_ASS WHERE UP_ID='" + permissionId + "'";
		List list = getJdbcTemplate().queryForList(sql);
		List haslist = new ArrayList();
		if(list!=null && list.size()>0){
			for (int i = 0; i < list.size(); i++) {
				ListOrderedMap map = (ListOrderedMap)list.get(i);
				haslist.add(map.get("UNIT_ID"));
			}
		}
		return haslist;
	}
}
